package com.kdtech.analyse.Answer;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.AnswerMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.analyse.utils.CollectionUtils;
/**
 * 搜狗问问
 * @author persh
 */
public class SogouswerAnalyse implements AnalyseAnswer {


	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		String[] regex = {
				"http://wenwen.sogou.com/z/q[0-9]*.htm\\?.*"
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public AnswerMeta parserHtml(UrlMeta urlMeta) {
		AnswerMeta answer = new AnswerMeta();
		if (urlMeta.getHtml() == null) {
		}
		String html = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		if(!isDetailPage(url)){
		}
		answer.setUrl(url);
		String title = null;
		Long date = null;
		String author = null;
		Document doc = Jsoup.parse(html);


		title =doc.select("title").text();
        if(title.indexOf("_")!=-1){
    	   title=title.substring(0,title.indexOf("_"));
        }
		date = DateUtils.matchDate(doc.select("span.time").text());
		author = doc.select("span.default-name").text();
		if(StringUtils.isBlank(author)){
			author = doc.select("a#ans_user_card_name0").text();
		}
		List<String> answser=new ArrayList<String>();
		Elements select = doc.select("div.answer-con");
		if(select!=null && select.size()!=0){
			for (Element element : select) {
				String html2 = HtmlCleaner.getContentHtml(url,element);
				answser.add(html2);
			}
		}
		String text = doc.select("div.l-ask").text();
		Integer clickNum = NumberUtils.matchNumber(StringUtils.substringBetween(text,"浏览","次"));

		answer.setTitle(StringUtils.trimSpace(title));
		answer.setDate(date);
		answer.setContent(CollectionUtils.join(answser, " "));
		answer.setAuthor(author);
		answer.setClickNum(clickNum);
		answer.setUpdateUrl(url);
		return answer;
	}
	
	public AnswerMeta Update(AnswerMeta meta) {
		String url = meta.getUpdateUrl();
		if (StringUtils.isNotBlank(url)){
			UrlMeta urlMeta = CrawlHTML.responseToURL(url);
			return parserHtml(urlMeta);
		}
		return null;
	}
	


	
}
